package com.gientech.group9.controller;

import com.gientech.group9.entity.User;
import com.gientech.group9.model.ApplyRecord;
import com.gientech.group9.model.AuditLog;
import com.gientech.group9.model.Ret;
import com.gientech.group9.model.valid.ApplyRecordSave;
import com.gientech.group9.service.ApplyRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@RestController
public class ApplyLornController {


    protected final Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private ApplyRecordService applyRecordService;

    @PostMapping("/customer/applyList")
    public Ret<List<ApplyRecord>> getApplyRecords(@RequestBody(required = false) ApplyRecord applyRecord) {
        List<ApplyRecord> applyRecords = applyRecordService.getApplyRecords(applyRecord, Sort.by("createDate").descending());
        return new Ret<>(200, applyRecords);
    }


    @PostMapping("customer/cancelApply")
    public Ret cancelApply(@RequestBody AuditLog auditLog) {
        auditLog.setStatus(-10);
        auditLog.setMemo(auditLog.getMemo());
        auditLog.setAuditDate(new Date());
        AuditLog audit = applyRecordService.audit(auditLog, false);
        return new Ret(200, null, "成功自行取消");
    }

    @GetMapping("/customer/applyRecord/{id}")
    public Ret<ApplyRecord> getApplyRecordById(@PathVariable("id") Integer applyId) {
        Optional<ApplyRecord> applyRecordById = applyRecordService.getApplyRecordById(applyId);
        return new Ret<>(200, applyRecordById != null && applyRecordById.isPresent() ? applyRecordById.get() : null);
    }


    /**
     * 贷款申请接口
     *
     * @param
     * @return
     */
    @PostMapping("/customer/submitApply")
    public Ret<ApplyRecord> addApplyRecord(@Validated({ApplyRecordSave.class}) @RequestBody ApplyRecord applyRecord, HttpServletRequest request) {
        applyRecord.setCreateDate(new Date());
        applyRecord.setStatus(0);
        ApplyRecord add = null;

        User user = (User) request.getSession().getAttribute("userInfo");
        if (user == null) {
            return new Ret<>(300, null, "请重新登录");
        }
        if (user != null) {
            applyRecord.setCustomerId(user.getUserId());
        }
        try {

            add = applyRecordService.save(applyRecord);
        } catch (RuntimeException e) {
            logger.error("applyRecordService error:", e);
            return new Ret<>(500, null, "添加失败");
        }
        return new Ret<>(200, add, "提交成功");
    }

    @PostMapping("/auditor/approve")
    public Ret<AuditLog> approve(@RequestBody AuditLog auditLog, HttpServletRequest request) {

        //1初审通过(Select) 2 合规性审核通过(Compliance) ,3信贷审批(Credit) 4 签订合同通过 (Contract) 5 贷款已发放(Repayment)


        switch (auditLog.getEvent()) {
            case "Select":
                auditLog.setStatus(1);
                break;
            case "Compliance":
                auditLog.setStatus(2);
                break;
            case "Credit":
                auditLog.setStatus(3);
                break;
            case "Contract":
                auditLog.setStatus(4);
                break;

            case "Finance":
                auditLog.setStatus(5);
                break;
            case "Repayment":
                auditLog.setStatus(6);
                break;
            default:
                throw new RuntimeException("状态异常");
        }
        Ret<AuditLog> audit = audit(auditLog, request, true);
        return audit;
    }

    @PostMapping("/auditor/deny")
    public Ret<AuditLog> deny(@RequestBody AuditLog auditLog, HttpServletRequest request) {
        switch (auditLog.getEvent()) {
            case "Select":
                auditLog.setStatus(-1);
                break;
            case "Compliance":
                auditLog.setStatus(-2);
                break;
            case "Credit":
                auditLog.setStatus(-3);
                break;
            case "Contract":
                auditLog.setStatus(-4);
                break;

            case "Finance":
                auditLog.setStatus(-5);
                break;
            case "Repayment":
                auditLog.setStatus(-6);
                break;
            default:
                throw new RuntimeException("状态异常");
        }
        return audit(auditLog, request, false);
    }

    private Ret<AuditLog> audit(AuditLog auditLog, HttpServletRequest request, Boolean approved) {

        User user = (User) request.getSession().getAttribute("userInfo");
        if (user != null) {
            auditLog.setAuditDate(new Date());

            auditLog.setAuditorUid(user.getUserId());
            auditLog.setAuditorName(user.getName());

            AuditLog save = null;
            try {
                save = applyRecordService.audit(auditLog, approved);
                return new Ret<>(200, save, "审核成功");
            } catch (RuntimeException e) {
                logger.error("audit error:", e);
                return new Ret<>(200, save, "审核失败");
            }
        } else {
            return new Ret<>(200, null, "未登录");
        }

    }


}
